package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 李旭
 * @date 2021/11/13 14:43
 * @Description:
 */
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;//从SpringIOC容器中获取出来

    //查询一级分类
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }
    //根据一级分类的ID 查询二级分类集合
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
         .eq("category1_id",category1Id));
    }
    //根据二级分类Id 查询三级分类集合
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }
    //根据分类的ID 查询平台属性及属性值集合
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }

    //保存平台属性及属性值
    @Override
    @Transactional //打开事务
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1:平台属性表  1
        baseAttrInfoMapper.insert(baseAttrInfo);//返回主键
        //2：平台属性值表 多
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){

            attrValueList.forEach(attrValue -> {
                //设置平台属性的外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);

            });
            //手写SQL 性能是非常高  同学们来批量保存完成一下
            //Mybatis 中 动态SQL <foreach>
            //insert into base_attr_value (id,value_name,attr_id) values (?,?,?),(?,?,?),(?,?,?)
        }


    }

    //品牌分页查询
    @Override
    public IPage<BaseTrademark> baseTrademarkList(Integer page, Integer limit) {

        Page<BaseTrademark> p = new Page<>(page, limit);


        return baseTrademarkMapper.selectPage(
                p,null);
    }
    //保存品牌
    @Override
    public void baseTrademarkSave(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    //查询商品的分页
    @Override
    public IPage<SpuInfo> spuPage(Integer page, Integer limit, Long category3Id) {

        return spuInfoMapper.selectPage(new Page<SpuInfo>(page,limit),
                 new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }
    //查询销售属性列表  /baseSaleAttrList
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {

        return baseSaleAttrMapper.selectList(null);
    }
    //查询品牌列表
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    //保存SPU
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1:商品表
        spuInfoMapper.insert(spuInfo);
        //2:图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断集合是否为NULl 长度是否大于0
        spuImageList.forEach(spuImage -> {
            //外键
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3:商品与销售属性表的关联表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            //外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4:商品与销售属性值的关联表
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                //销售属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                //外键
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });

        });
    }
    //库存 SKu分页查询
    @Override
    public IPage skuPage(Integer page, Integer limit) {

        return skuInfoMapper.selectPage(new Page<SkuInfo>(page,limit),null);
    }
    //根据spuId 查询 商品的所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
          .eq("spu_id",spuId));
    }
    //根据spuId 查询销售属性及属性值
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }
    //保存 SKUInfo
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
//        1、Sku_info   核心表
        skuInfoMapper.insert(skuInfo);
//            |--2、sku_image库存的图片表   某一个颜色的所有图片
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            //外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
//                |--3、sku_attr_value 库存的平台属性及属性值表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
//                |--4、sku_sale_attr_value 库存的销售属性及属性值表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            //skuId
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spuId
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });


    }

    @Autowired
    private RabbitService rabbitService;
    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);//解决 硬编码问题
        skuInfoMapper.updateById(skuInfo);// update sku_info set is_sale = 1 where id = ?
        //发消息通知搜索微服务 添加商品的索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                 MqConst.ROUTING_GOODS_UPPER,skuId);

    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);//解决 硬编码问题
        skuInfoMapper.updateById(skuInfo);// update sku_info set is_sale = 0 where id = ?
        //发消息通知搜索微服务 删除商品索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }
    //库存信息 及库存的图片  条件：库存Id
  /*  @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;  //本次是查询SkuInfo的数据 拼接了 skuId
        //1:查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2:有 直接返回
        if(null == skuInfo){
            //3:没有 查询DB
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //UUID  判断是否为自己的锁的唯一标识
            String uuid = UUID.randomUUID().toString();
            //3.1 查询DB之前要求加锁 以防止是热点数据  大量请求 只能通过一个
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid
                                          ,1,TimeUnit.SECONDS);
            if(isLock){
                //获取到了锁
                //库存信息
                try {
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if(null != skuInfo){
                        //库存的图片
                        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);
                        //4:再保存一份到缓存中
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), //解决缓存雪崩
                                TimeUnit.SECONDS);//过期时间一天+随机数（5分钟之内）
                    }else{
                        //代码能执行在此处  说明DB中也没有数据
                        //缓存的穿透问题  不让访问把DB弄挂掉
                        //将空结果保存到缓存中
                        skuInfo = new SkuInfo();// 不是NULL 是空结果  结果是skuInfo对象 对象中没有数据 叫空结果
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);//过期时间是5分钟
                    }
                } finally {
                    //判断是否是自己的锁
                    //1:是自己的锁
                *//*    Object u = redisTemplate.opsForValue().get(cacheLockKey);
                    //2:不是自己的锁
                    if(uuid.equals(u)){
                        //自己的锁    //删除不具备原子性   时间差
                        //3:解锁  解了别人的锁
                        redisTemplate.delete(cacheLockKey);
                    }*//*
                    //准备 LUA脚本
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    //执行此脚本    Redis是单线程 （Redis自己就是原子性
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);

                }
            }else{
                //未获取到锁  去获取缓存数据即可
                try {
                    TimeUnit.SECONDS.sleep(1);//1S   时间差
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
            }

        }
        //5：统一返回
        return skuInfo;
    }*/

    /**
     * 使用RedissonClient来实现分布式锁
     *    就是当本地锁的方式来使用就可以实现分布式锁
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;  //本次是查询SkuInfo的数据 拼接了 skuId
        //1:查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2:有 直接返回
        if(null == skuInfo){
            //3:没有 查询DB
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //3.1:加锁
            RLock lock = redissonClient.getLock(cacheLockKey);
            //过期不候的锁
            //参数1： 过期不候的过期是多长时间
            //参数2： 获取到锁之后 锁的过期时间
            //参数3： 单位
            try {
                boolean isLock = lock.tryLock(1, 1, TimeUnit.SECONDS);
                if(isLock){
                    //获取到了锁
                    //库存信息
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if(null != skuInfo){
                            //库存的图片
                            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId));
                            skuInfo.setSkuImageList(skuImageList);
                            //4:再保存一份到缓存中
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), //解决缓存雪崩
                                    TimeUnit.SECONDS);//过期时间一天+随机数（5分钟之内）
                        }else{
                            //代码能执行在此处  说明DB中也没有数据
                            //缓存的穿透问题  不让访问把DB弄挂掉
                            //将空结果保存到缓存中
                            skuInfo = new SkuInfo();// 不是NULL 是空结果  结果是skuInfo对象 对象中没有数据 叫空结果
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);//过期时间是5分钟
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else{
                    //未获取到锁  去获取缓存数据即可
                    try {
                        TimeUnit.SECONDS.sleep(1);//1S   时间差
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //5：统一返回
        return skuInfo;
    }


    //上面的库存信息中有三级分类的ID  所以才可以查询一二三级分类
    //加入缓存
    @Override
    @Transactional  //事务注解
    @GmallCache(prefix="basCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //要求价格单独查询   从MySQL中查询
    @Override
    public BigDecimal getPrice(Long skuId) {
        // select * from sku_info where id = ?
        // select price from sku_info where id = ?
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",skuId);
        queryWrapper.select("price");
        SkuInfo skuInfo = skuInfoMapper.selectOne(queryWrapper);
        if(null != skuInfo){
            return skuInfo.getPrice();
        }
        return null;
    }

    //查询销售属性及属性值并选中
    @Override
    @GmallCache(prefix="selectSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> selectSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(spuId,skuId);
    }

    //组合数据 对应 skuId
    @Override
    @GmallCache(prefix="getSaleAttrValuesBySpu")
    public Map getSaleAttrValuesBySpu(Long spuId) {
        List<Map> listMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
//        List<Map>  listMap
//        Map1:  K :value_ids  V: 1|5|7
//        K:sku_id   V:1
//        Map2:  K :value_ids  V: 1|5|9
//        K:sku_id   V:2
// {颜色|版本|套装 : skuId,颜色|版本|套装 : skuId,颜色|版本|套装 : skuId,颜色|版本|套装 : skuId}
        //Map  K:颜色|版本|套装 V:skuId
        Map result = new HashMap();
        listMap.forEach(map -> {
            result.put(map.get("value_ids"),map.get("sku_id"));
        });
        return result;
    }

    //查询分类视图中所有的分类数据
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
    //skuInfo与平台属性及值的关联数据
    @Override
    public List<SkuAttrValue> getSkuAttrValueList(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValueList(skuId);
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

}
